import wareahouseService, { type PageListReq } from "@/api/services/wms/warehouseService";
import TableDictTag from "@/components/grid/TableDictTag";
import { TableToolbar } from "@/components/grid/TableToolbar";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import {
	Button,
	Card,
	Col,
	Drawer,
	Empty,
	Form,
	Input,
	InputNumber,
	Row,
	Select,
	Space,
	Spin,
	Switch,
	Tabs,
	Tree,
	TreeSelect,
} from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { debounce } from "lodash-es";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import type { WmsWarehouse } from "./entity";
import WarehouseUser,  { type WarehouseUserHandles } from "./warehouseUser";

const { TextArea } = Input;

export default function WmsWarehousePage() {
	//获取子类组件ref
	const warehouseUserRef = useRef<WarehouseUserHandles>(null);

	const [loading, setLoading] = useState(false);
	const [treeLoading, setTreeLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		code: undefined,
		name: undefined,
		enableFlag: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<WmsWarehouse[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<WmsWarehouse | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	const [treeList, setTreeList] = useState<WmsWarehouse[]>([]);
	const [selectWarehouse, setSelectWarehouse] = useState<WmsWarehouse | null>(null);
	const [searchValue, setSearchValue] = useState("");

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	const typeOptions = useDictionary("warehouse_type");
	const areaFlagOptions = useDictionary("system_true_false");

	const columns: ColumnsType<WmsWarehouse> = [
		{
			title: "类型",
			width: 120,
			key: "type",
			dataIndex: "type",
			render: (_, record) => <TableDictTag dictCode="warehouse_type" value={record.type} />,
		},
		{
			title: "仓库编码",
			width: 120,
			key: "code",
			dataIndex: "code",
		},
		{
			title: "仓库名称",
			width: 120,
			key: "name",
			dataIndex: "name",
		},
		{
			title: "库位管理",
			width: 120,
			key: "areaFlag",
			dataIndex: "areaFlag",
			render: (_, record) => <TableDictTag dictCode="system_true_false" value={record.areaFlag ?? ""} />,
		},
		{
			title: "是否启用",
			width: 120,
			key: "enableFlag",
			dataIndex: "enableFlag",
			render: (_, record) => <TableDictTag dictCode="system_true_false" value={record.enableFlag ?? ""} />,
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => (col.key ? String(col.key) : "")),
	);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		wareahouseService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	//加载树形结构数据
	const fetchTreeList = async () => {
		setTreeLoading(true);
		await wareahouseService
			.treeList(queryParams)
			.then((data) => {
				if (data) {
					setTreeList(data);
				}
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setTreeLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchTreeList();
	}, []);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (wmsWarehouse: WmsWarehouse) => {
		setEditingData(wmsWarehouse);
		form.setFieldsValue(wmsWarehouse);
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (wmsWarehouse: WmsWarehouse) => {
		setEditingData(wmsWarehouse);
		form.setFieldsValue(wmsWarehouse);
		setIsView(true);
		setDrawerVisible(true);
	};

	//提交表单数据
	const handleSubmit = async (values: WmsWarehouse) => {
		try {
			setLoading(true);

			// 安全调用 
			const deleteUserIds = warehouseUserRef.current?.getDeleteUserIds?.()  || [];
			const insertUserIds = warehouseUserRef.current?.getNewUserIds?.()  || [];

			if (editingData) {
				await wareahouseService.update({ ...values, id: editingData.id, deleteUserIds, insertUserIds  });
				toast.success("更新仓库成功");
			} else {
				await wareahouseService.add({...values, deleteUserIds, insertUserIds });
				toast.success("创建仓库成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
			fetchTreeList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAddWarehouse = () => {
		setEditingData(null);
		form.resetFields();
		form.setFieldValue("parentId", null);
		form.setFieldValue("type", "warehouse");
		form.setFieldValue("enableFlag", "1");
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleAdd = () => {
		if (!selectWarehouse) {
			toast.error("请先选择仓库或区域");
			return;
		}
		setEditingData(null);
		form.resetFields();
		form.setFieldValue("parentId", selectWarehouse?.id);
		if (selectWarehouse?.type === "warehouse") {
			form.setFieldValue("type", "location");
		} else if (selectWarehouse?.type === "location") {
			form.setFieldValue("type", "area");
		}

		form.setFieldValue("enableFlag", "1");
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await wareahouseService.remove(selectedRowKeys);
			toast.success("删除仓库成功");
			setSelectedRowKeys([]);
			fetchPageList();
			fetchTreeList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	// 过滤树数据（递归搜索）
	const filteredTreeData = useMemo(() => {
		// 无搜索值时返回完整数据
		if (!searchValue) return treeList;

		const loop = (data: WmsWarehouse[]): WmsWarehouse[] => {
			return data
				.map((item) => {
					const match = item.name.toLowerCase().includes(searchValue.toLowerCase());
					const children = item.children ? loop(item.children) : undefined;
					const hasChildMatch = children && children.length > 0;

					return match || hasChildMatch ? { ...item, children } : null;
				})
				.filter(Boolean) as WmsWarehouse[];
		};

		return loop(treeList);
	}, [treeList, searchValue]);

	// 递归查找节点数据
	const findNodeById = useCallback((id: string, nodes: WmsWarehouse[]): WmsWarehouse | undefined => {
		for (const node of nodes) {
			if (node.id === id) return node;
			if (node.children) {
				const found = findNodeById(id, node.children);
				if (found) return found;
			}
		}
		return undefined;
	}, []);

	// 处理树节点点击
	const handleNodeSelect = useCallback(
		(selectedKeys: React.Key[]) => {
			if (selectedKeys.length === 0) {
				setSelectWarehouse(null);
				return;
			}

			const selectedId = selectedKeys[0] as string;
			const foundNode = findNodeById(selectedId, treeList);

			if (foundNode) {
				setSelectWarehouse(foundNode);
				setQueryParams((prev) => ({
					...prev,
					parentId: selectedId,
					page: 1,
				}));
			}
		},
		[treeList, findNodeById],
	);

	// 防抖处理搜索输入
	const handleSearch = debounce((value: string) => {
		setSearchValue(value);
	}, 300);

	return (
		<>
			<Row gutter={16} className="h-[calc(100vh-120px)]">
				{/* 左侧树形结构 */}
				<Col span={5} className="h-full">
					<Card className="h-full overflow-auto" bodyStyle={{ height: "100%", padding: "16px" }}>
						<Input.Search
							placeholder="搜索仓库"
							onChange={(e) => handleSearch(e.target.value)}
							allowClear
							className="mb-4"
						/>
						{treeLoading ? (
							<Spin spinning tip="加载中..." />
						) : filteredTreeData.length === 0 ? (
							<Empty description={searchValue ? "无匹配结果" : "暂无数据"} />
						) : (
							<Tree
								treeData={filteredTreeData}
								fieldNames={{ key: "id", children: "children", title: "name" }}
								titleRender={(node: WmsWarehouse) => (
									<div style={{ display: "flex", alignItems: "center" }}>
										<span className="mr-2">{node.name}</span>
										{node.type && <TableDictTag dictCode="warehouse_type" value={node.type} />}
									</div>
								)}
								onSelect={handleNodeSelect}
							/>
						)}
					</Card>
				</Col>
				{/* 右侧内容区 */}
				<Col span={19}>
					<Card className="mb-4">
						<Form
							layout="inline"
							onFinish={(values) => {
								setQueryParams((prev) => ({
									...prev,
									...values,
									page: 1,
								}));
							}}
						>
							<Row gutter={16}>
								<Col span={6}>
									<Form.Item name="code" label="仓库编码">
										<Input placeholder="请输入仓库编码" allowClear />
									</Form.Item>
								</Col>
								<Col span={6}>
									<Form.Item name="name" label="仓库名称">
										<Input placeholder="请输入仓库名称" allowClear />
									</Form.Item>
								</Col>
								<Col span={6}>
									<Form.Item name="enableFlag" label="是否启用">
										<Input placeholder="请输入是否启用" allowClear />
									</Form.Item>
								</Col>
								<Col span={6}>
									<Form.Item className="flex justify-end mb-0">
										<Button type="primary" htmlType="submit">
											查询
										</Button>
										<Button
											className="ml-2"
											onClick={() => {
												setQueryParams({ page: 1, pageSize: 10 });
											}}
										>
											重置
										</Button>
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</Card>
					<div className="h-4" />
					<Card>
						<div className="flex justify-between mb-4">
							<div className="flex gap-2">
								<Button type="primary" onClick={handleAddWarehouse}>
									新增仓库
								</Button>
								<Button type="primary" onClick={handleAdd}>
									新增子区域
								</Button>
								<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
									删除
								</Button>
							</div>
							<TableToolbar
								onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
								onSizeChange={setTableSize}
								columns={columns}
								selectedValues={selectedValues}
								onColumnChange={setSelectedValues}
							/>
						</div>
						<Table
							rowKey="id"
							size={tableSize}
							scroll={{ x: "max-content", y: tableScrollY }}
							loading={loading}
							pagination={{
								total,
								current: queryParams.page,
								pageSize: queryParams.pageSize,
								onChange: handlePageChange,
							}}
							columns={filteredColumns}
							dataSource={list}
							rowSelection={{
								type: "checkbox",
								selectedRowKeys: selectedRowKeys,
								onChange: (selectedKeys) => {
									setSelectedRowKeys(selectedKeys as string[]);
								},
							}}
						/>
					</Card>
				</Col>
			</Row>

			<Drawer
				title={editingData ? "编辑仓库" : "新增仓库"}
				width={500}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					{form.getFieldValue("type") !== "warehouse" && (
						<Form.Item name="parentId" label="上级">
							<TreeSelect
								disabled
								fieldNames={{
									label: "name",
									value: "id",
									children: "children",
								}}
								treeData={treeList}
							/>
						</Form.Item>
					)}
					<Form.Item name="type" label="类型">
						<Select options={typeOptions} allowClear disabled/>
					</Form.Item>
					<Form.Item
						name="code"
						label="仓库编码"
						rules={[
							{
								required: true,
								message: "请填写仓库编码",
							},
						]}
					>
						<Input placeholder="请输入仓库编码" allowClear />
					</Form.Item>
					<Form.Item
						name="name"
						label="仓库名称"
						rules={[
							{
								required: true,
								message: "请填写仓库名称",
							},
						]}
					>
						<Input placeholder="请输入仓库名称" allowClear />
					</Form.Item>
					{form.getFieldValue("type") === "warehouse" && (
						<>
							<Form.Item name="location" label="位置">
								<Input />
							</Form.Item>
							<Form.Item name="area" label="面积">
								<InputNumber placeholder="请输入面积" style={{ width: "100%" }} addonAfter="㎡" />
							</Form.Item>
						</>
					)}
					{form.getFieldValue("type") === "area" && (
						<>
							<Form.Item name="areaFlag" label="是否开启库位管理">
								<Select options={areaFlagOptions} allowClear />
							</Form.Item>
							<Form.Item name="maxLoa" label="最大载重量">
								<InputNumber placeholder="请输入最大载重量" style={{ width: "100%" }} addonAfter="kg" />
							</Form.Item>
						</>
					)}
					<Form.Item
						name="enableFlag"
						label="是否启用"
						rules={[
							{
								required: true,
								message: "请填写是否启用",
							},
						]}
					>
						<Switch
							checkedChildren="是"
							unCheckedChildren="否"
							checkedValue="1"
							unCheckedValue="0"
							disabled={isView}
						/>
					</Form.Item>
					<Form.Item name="remark" label="备注">
						<TextArea />
					</Form.Item>

					{form.getFieldValue("type") === "warehouse" && (
						<Tabs defaultActiveKey="1" items={
							[{
								key: '1',
								label: '仓管员',
								children: <WarehouseUser ref={warehouseUserRef} warehouseId={form.getFieldValue("id")}/>,
							}]
						}  />
					)}
				</Form>
			</Drawer>
		</>
	);
}
